/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "FractalTerrainGenerateDialog.h"
#include "FractalGenerator.h"

namespace PQBuilder
{
	FractalTerrainGenerateDialog::FractalTerrainGenerateDialog(QWidget* parent)
		: QDialog(parent),_ui(new Ui::FractalTerrainGenerateDialogUI),
		_graphicsScene(new QGraphicsScene()),_terrainSize(512),_randomSeed(0),_valueH(0.5)
	{
		_ui->setupUi(this);
		_ui->graphicsView->setScene(_graphicsScene);
		_ui->sizeCombo->addItem(QObject::tr("512"));
		_ui->sizeCombo->addItem(QObject::tr("1024"));
		_ui->sizeCombo->addItem(QObject::tr("2048"));
		_ui->sizeCombo->addItem(QObject::tr("4096"));
		
		
		connect(_ui->sizeCombo,SIGNAL(currentIndexChanged(int)),this,SLOT(selectTerrainSize(int)));
		connect(_ui->generateButton, SIGNAL(clicked()), this, SLOT(generateFractalTerrain()));
		connect(_ui->randomButton, SIGNAL(clicked()), this, SLOT(randomTerrain()));
		connect(_ui->HValueSlider,SIGNAL(valueChanged(int)),this,SLOT(valueHChanged(int)));
		this->setModal(true);

	}

	void FractalTerrainGenerateDialog::generateFractalTerrain()
	{
		_randomSeed=_ui->seedSpin->value();
		SFractalTerrainGenerator.generate(_terrainSize,_randomSeed,255,_valueH);
		QImage image(_terrainSize+1, _terrainSize+1, QImage::Format_RGB32);
		QRgb value;


		for(int i=0;i<_terrainSize+1;i++){
			for(int j=0;j<_terrainSize+1;j++){
				float v= SFractalTerrainGenerator.get(i,j)+128;
				if(v<0){
					v=0;
				}
				value = qRgb(v, v, v);
				image.setPixel(i, j, value);
			}
		}
		
		QPixmap pixmap=QPixmap::fromImage(image);
		_graphicsScene->clear();
		
		_graphicsScene->addPixmap(pixmap);
		
	}

	void FractalTerrainGenerateDialog::selectTerrainSize(int index)
	{
		switch(index){
			case 0:
				_terrainSize=512;
				break;
			case 1:
				_terrainSize=1024;
				break;
			case 2:
				_terrainSize=2048;
				break;
			case 3:
				_terrainSize=4096;
				break;
			default:
				_terrainSize=512;
				break;
		}
	}

	void FractalTerrainGenerateDialog::valueHChanged(int v)
	{
		float value=_ui->HValueSlider->value();
		_valueH=value/100.0f;
		QString text,numText;
		numText.setNum(_valueH);
		text="H:"+numText;
		_ui->HValueLable->setText(text);

	}

	void FractalTerrainGenerateDialog::randomTerrain()
	{
		srand((unsigned int)time(0));
		_randomSeed= PQEngine::MathUtil::randFloat(0,32767);
		_ui->seedSpin->setValue(_randomSeed);
	}
}
